package com.ohos.connect.devicecloud.app.modular.projectuser.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ohos.connect.devicecloud.app.modular.projectuser.model.dto.ProjectUserSearchDTO;
import com.ohos.connect.devicecloud.auth.core.util.StpAppLoginUserUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ohos.connect.devicecloud.common.enums.CommonSortOrderEnum;
import com.ohos.connect.devicecloud.common.exception.CommonException;
import com.ohos.connect.devicecloud.common.page.CommonPageRequest;
import com.ohos.connect.devicecloud.app.modular.projectuser.model.entity.ProjectUser;
import com.ohos.connect.devicecloud.app.modular.projectuser.mapper.ProjectUserMapper;
import com.ohos.connect.devicecloud.app.modular.projectuser.model.dto.ProjectUserAddDTO;
import com.ohos.connect.devicecloud.app.modular.projectuser.param.ProjectUserEditParam;
import com.ohos.connect.devicecloud.app.modular.projectuser.param.ProjectUserIdParam;
import com.ohos.connect.devicecloud.app.modular.projectuser.param.ProjectUserPageParam;
import com.ohos.connect.devicecloud.app.modular.projectuser.service.ProjectUserService;

import java.util.List;

/**
 * APP项目用户Service接口实现类
 *
 * @author Dongtao
 * @date  2024/12/05 11:05
 **/
@Service
public class ProjectUserServiceImpl extends ServiceImpl<ProjectUserMapper, ProjectUser> implements ProjectUserService {

    @Override
    public String getUserIdByProjectId(String projectId) {
        if (StrUtil.isBlank(projectId)) {
            throw new CommonException("项目id不能为空");
        }
        QueryWrapper<ProjectUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("project_id", projectId);
        ProjectUser projectUser = getOne(queryWrapper);
        if(ObjectUtil.isNotNull(projectUser)) {
            return  projectUser.getAppUserId();
        }
        return "";
    }

    @Override
    public Page<ProjectUser> page(ProjectUserPageParam projectUserPageParam) {
        QueryWrapper<ProjectUser> queryWrapper = new QueryWrapper<>();
        if(ObjectUtil.isAllNotEmpty(projectUserPageParam.getSortField(), projectUserPageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(projectUserPageParam.getSortOrder());
            queryWrapper.orderBy(true, projectUserPageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(projectUserPageParam.getSortField()));
        } else {
            queryWrapper.lambda().orderByAsc(ProjectUser::getId);
        }
        return this.page(CommonPageRequest.defaultPage(), queryWrapper);
    }

    @Override
    public List<ProjectUser> getProjectsByAppUserId(ProjectUserSearchDTO projectUserSearchDTO){
        QueryWrapper<ProjectUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ProjectUser::getAppUserId, projectUserSearchDTO.getAppUserId());

        return this.list(queryWrapper);
    }

    // 获取项目用户，并校验
    @Override
    public ProjectUser getProjectUserByProjectId(String projectId){
        if(ObjectUtil.isEmpty(projectId)){
            throw new CommonException("项目id不能为空");
        }
        String userId = StpAppLoginUserUtil.getAppLoginUserId();
        QueryWrapper<ProjectUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(ProjectUser::getProjectId,projectId)
                .eq(ProjectUser::getAppUserId,userId);

        ProjectUser projectUser = this.getOne(queryWrapper);
        if(ObjectUtil.isEmpty(projectUser)){
            throw new CommonException("当前用户无权访问该项目，项目id: "+projectId);
        }
        return projectUser;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean add(ProjectUserAddDTO projectUserAddDTO) {
        ProjectUser projectUser = BeanUtil.toBean(projectUserAddDTO, ProjectUser.class);
        return this.save(projectUser);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(ProjectUserEditParam projectUserEditParam) {
        ProjectUser projectUser = this.queryEntity(projectUserEditParam.getId());
        BeanUtil.copyProperties(projectUserEditParam, projectUser);
        this.updateById(projectUser);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<ProjectUserIdParam> projectUserIdParamList) {
        // 执行删除
        this.removeByIds(CollStreamUtil.toList(projectUserIdParamList, ProjectUserIdParam::getId));
    }

    @Override
    public ProjectUser detail(ProjectUserIdParam projectUserIdParam) {
        return this.queryEntity(projectUserIdParam.getId());
    }

    @Override
    public ProjectUser queryEntity(String id) {
        ProjectUser projectUser = this.getById(id);
        if(ObjectUtil.isEmpty(projectUser)) {
            throw new CommonException("APP项目用户不存在，id值为：{}", id);
        }
        return projectUser;
    }
}
